/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.oss.cloud;

import com.aliyun.oss.OSSClient;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;

import io.renren.modules.oss.config.CloudStorageConfig;
import io.renren.modules.oss.dto.UploadResultDTO;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AliyunCloudStorageService extends AbstractCloudStorageService {

  public AliyunCloudStorageService(CloudStorageConfig config) {
    this.config = config;
  }

  @Override
  public UploadResultDTO upload(byte[] data, String path) {
    return upload(new ByteArrayInputStream(data), path);
  }

  @Override
  public UploadResultDTO upload(InputStream inputStream, String path) {
    OSSClient client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
        config.getAliyunAccessKeySecret());
    try {
      client.putObject(config.getAliyunBucketName(), path, inputStream);
      client.shutdown();
    } catch (Exception e) {
      throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
    }

    return new UploadResultDTO(config.getAliyunDomain() + "/" + path,
        config.getAliyunDomain() + "/" + path);
  }

  @Override
  public UploadResultDTO uploadSuffix(byte[] data, String suffix) {
    return upload(data, getPath(config.getAliyunPrefix(), suffix));
  }

  @Override
  public UploadResultDTO uploadSuffix(InputStream inputStream, String suffix) {
    return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
  }

  /**
   * 组装下载路径
   */
  @Override
  public UploadResultDTO handleDownloadUrl(UploadResultDTO uploadResultDTO) {
    return null;
  }
}
